<?php

/*
 * IWA project - TrainManager.php
 * Maximilian Einoeder
 * Mark Mensing
 * 
 * Class to plan a route with the dutch railways API.
 */

//Connection values
$uname = 'langerkanniet@gmail.com';
$pwd = 'IAoV4OhtZC9LnxYDhn9HCp8TtAnd3-wlfca_wriQQctaosaUjyaegg';

class TrainManager {

    //Connect to a specific url, returns a xml result
    public function connect($urlInput, $user, $pass) {
        //Make the call to the ns api
        $ch = curl_init($urlInput);
        curl_setopt($ch, CURLOPT_HEADER, false);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
        curl_setopt($ch, CURLOPT_USERPWD, $user . ':' . $pass);
        $response = curl_exec($ch);
        curl_close($ch);
        return new SimpleXMLElement($response);
    }

    //Finds the quickest train possibility returns a ReisMogelijkheid xml
    public function getQuickest($xmlInput) {
        $index = 0;
        $lowest = strtotime($xmlInput->ReisMogelijkheid[0]->GeplandeReisTijd);

        for ($i = 1; $i > 5; $i++) {
            if ($lowest > strtotime($xmlInput->ReisMogelijkheid[$i]->GeplandeReisTijd)) {
                $index = $i;
                $lowest = strtotime($xmlInput->ReisMogelijkheid[$i]->GeplandeReisTijd);
            }
        }

        return $xmlInput->ReisMogelijkheid[$index];
    }

    /*
     * Return a 2d array filled with the stops the quickest journey has.
     * The array contain sub-arrays that have the following info:
     * [0] Name of the station
     * [1] Time of departure
     * [2] Which platform the train arrives
     */

    public function getStops($xmlInput) {
        //First determine the quickest journey of the 5 given suggestions
        $journey = TrainManager::getQuickest($xmlInput);

        $result = array();

        //Now extract the stops
        foreach ($journey->ReisDeel as $part) {
            if ($part["reisSoort"] == "TRAIN") {
                //Get the name of each stop
                foreach ($part->ReisStop as $stop) {
                    $traininfo = array(trim((string) $stop->Naam), trim((string) $stop->Tijd), trim((string) $stop->Spoor));
                    $result[] = $traininfo;
                }
            }
        }	

        return $result;
    }

}

?>